﻿using System.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Marbles.Core.Web.Cart.StateProviders
{
    public class CartSessionStateProvider : CartStateProvider, ICartStateProvider
    {
        public Cart CurrentCart
        {
            get
            {
                object key = HttpContext.Current.Session["CART_KEY"];
                if (key == null) { return null; }
                Cart cart = HttpContext.Current.Session[key.ToString()] as Cart;
                return cart;
            }
            set
            {
                HttpContext.Current.Session[value.ID] = value;
            }
        }

        public Cart CreateCart()
        {
            Cart cart = new Cart();
            HttpContext.Current.Session.Add(cart.ID, cart);
            HttpContext.Current.Session.Add("CART_KEY", cart.ID);
            return cart;
        }

        public void DestroyCart(Cart Cart)
        {
            string key = HttpContext.Current.Session["CART_KEY"] as string;

            if (key != string.Empty)
            {
                HttpContext.Current.Session["CART_KEY"] = null;
                HttpContext.Current.Session.Remove("CART_KEY");
                HttpContext.Current.Session[key] = null;
                HttpContext.Current.Session.Remove(key);
            }

            HttpContext.Current.Session[Cart.ID] = null;
            HttpContext.Current.Session.Remove(Cart.ID);
        }
    }
}
